import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_aygsh/base/Constant.dart';
import 'package:flutter_aygsh/http/HttpUtil.dart';
import 'package:flutter_aygsh/http/Api.dart';
import '../util/SignUtil.dart';
import '../entity/cate_entity.dart';
import '../liz_home/goods/ShopGoodsListNoCate.dart';
class SubCate extends StatefulWidget {
  SubCate({Key key}) : super(key: key);

  @override
  _SubCateState createState() => _SubCateState();
}

class _SubCateState extends State<SubCate> with AutomaticKeepAliveClientMixin{
  
  int _selectIndex = 0;
  List _leftCateList = [];
  List _rightCateList = [];
  @override
  bool get wantKeepAlive =>true;

  @override
  void initState() {
    super.initState();
    _getLeftCateData();
  }

  //左侧数据：
  _getLeftCateData() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_GOODSCAT_PARENTLIST),
    });

    // FormData data = new FormData.fromMap({});
    Response<String> response =
        await HttpUtil().post(Api.URL_GOODSCAT_PARENTLIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    // print('左侧');
    // print(userMap);
    CateModelEntity itemEntity = new CateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          _leftCateList.clear();
          _leftCateList = itemEntity.data;
          _getRightCateData(_leftCateList[0].cat_id);
        });
      }
    }
  }

  //右侧数据：
  _getRightCateData(pid) async {
        Map map = new Map.from({
      "sign_type": createSignType(Api.URL_GOODSCAT_SUBLIST),
      'pid': pid
    });
    Response<String> response =
        await HttpUtil().post(Api.URL_GOODSCAT_SUBLIST, data:  getSign(map));
    Map userMap = json.decode(response.data);
    // print('右侧');
    // print(userMap);
    CateModelEntity itemEntity = new CateModelEntity.fromJson(userMap);
    if (itemEntity.code == 1) {
      if (mounted) {
        setState(() {
          _rightCateList.clear();
          _rightCateList = itemEntity.data;
        });
      }
    }
  }

  //左侧组件
  Widget _leftCateWidget(leftWidth) {
    if (this._leftCateList.length > 0) {
      return Container(
        width: leftWidth,
        height: double.infinity,
        // color: Colors.red,
        child: ListView.builder(
          itemCount: this._leftCateList.length,
          itemBuilder: (context, index) {
            return Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    setState(() {
                      // setState(() {
                      _selectIndex = index;
                      this._getRightCateData(this._leftCateList[index].cat_id);
                    });
                    print(_selectIndex);
                  },
                  child: Container(
                    width: double.infinity,
                    height: ScreenUtil().setHeight(80),
                    padding: EdgeInsets.all(kMargin20),
                    child: Text("${this._leftCateList[index].cat_name}",
                        textAlign: TextAlign.center,style: TextStyle(fontSize:ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE))),
                    color: _selectIndex == index
                        ? Color.fromRGBO(240, 246, 246, 0.9)
                        : Colors.white,
                  ),
                ),
                Divider(height: 1),
              ],
            );
          },
        ),
      );
    } else {
      return Container(
        width: leftWidth,
        height: double.infinity,
      );
    }
  }

  //右侧组件：
  Widget _rightCateWidget(rightItemWidth, rightItemHeigth) {
    if (this._rightCateList.length > 0) {
      return Expanded(
        flex: 1,
        child: Container(
          padding: EdgeInsets.all(10),
          height: double.infinity,
          color: Color.fromRGBO(240, 246, 246, 0.9),
          // color: Colors.blue,
          child: GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                childAspectRatio: 0.8,
                crossAxisSpacing: kMargin20*4,
                mainAxisSpacing: kMargin20),
            itemCount: this._rightCateList.length,
            itemBuilder: (context, index) {
              return GestureDetector(
                onTap: (){
                  Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return new ShopGoodsListNoCatePage(
                                cat_id: this._rightCateList[index].cat_id,
                                name: this._rightCateList[index].cat_name,
                                
                              );
                            }));
                },
                child: Container(
                // padding: EdgeInsets.all(ScreenAdaper.width(20)),
                child: Column(
                  children: <Widget>[
                    ClipOval(
                        // child:
                      child:this._rightCateList[index].img==null||this._rightCateList[index].img==''?Image.asset('images/pic_default.png',
                            width: ScreenUtil.getInstance().setWidth(DP_90),
                            height: ScreenUtil.getInstance().setWidth(DP_90)): Image.network(
                          Api.BaseUrl+'public/upload/'+this._rightCateList[index].img.replaceAll('\\', '/'),
                          fit: BoxFit.cover, width: ScreenUtil.getInstance().setWidth(DP_90),
                            height: ScreenUtil.getInstance().setWidth(DP_90)),
                    ),
                    Container(
                      height: ScreenUtil().setHeight(29),
                      child: Text("${this._rightCateList[index].cat_name}",style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(25)),),
                    )
                  ],
                ),
              )
              ) ;
            },
          ),
        ),
      );
    } else {
      return Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.all(10),
            height: double.infinity,
            color: Color.fromRGBO(240, 246, 246, 0.9),
            child:Center(child: Text('暂无')) ,
          ));
    }
  }

  Widget build(BuildContext context) {
    //计算右侧GridView宽高比：
    var leftWidth = ScreenUtil.getInstance().setWidth(750) / 4;
    //右侧宽高=总宽度-左侧宽度-Gridview外层元素左右的Padding值-GridView中间的间距
    var rightItemWidth = (ScreenUtil.getInstance().setWidth(750) - leftWidth - 20 - 20) / 3;
    rightItemWidth = ScreenUtil().setWidth(rightItemWidth);
    var rightItemHeigth = rightItemWidth + ScreenUtil().setHeight(32);

    return Scaffold(
        body: Row(
          children: <Widget>[
            _leftCateWidget(leftWidth),
            _rightCateWidget(rightItemWidth, rightItemHeigth)
          ],
        ));
  }
}